"""
项目：Ai-Engineer自适应工程设计自动化插件
作者：刘昊轩、李佳音、刘伟伟、杨明久（排序不分先后）
©版权保护
"""
# src/ai_integration/deepseek_client.py
import os
from typing import Dict, Any
import requests
from dotenv import load_dotenv
from utilities import get_response

load_dotenv()


class OfficialDeepSeekClient:
    """DeepSeek官方API客户端"""

    def __init__(self):
        self.base_url = "https://api.deepseek.com/v1"
        self.api_key = os.getenv("DEEPSEEK_OFFICIAL_KEY")
        self.deepseek = get_response.Deepseek()

        if not self.api_key:
            raise ValueError("未配置官方API密钥")

    def generate(self, prompt: str, model: str = "deepseek-chat", **kwargs) -> str:
        """
        调用DeepSeek官方API生成内容
        文档：https://api-docs.deepseek.com/zh-cn/
        """
        try:
            response = self.deepseek.chat_completions(prompt, model, **kwargs)
            response.raise_for_status()
            return self._parse_response(response.json())
        except requests.exceptions.RequestException as e:
            if e.response.status_code == 429:
                raise RateLimitError("API请求速率限制")
            raise RuntimeError(f"API请求失败: {str(e)}")

    def _parse_response(self, data: Dict[str, Any]) -> str:
        """解析API响应"""
        if "choices" not in data or len(data["choices"]) == 0:
            raise ValueError("响应格式异常：未找到有效结果")

        return data["choices"][0]["message"]["content"]

    def list_models(self) -> Dict[str, Any]:
        """获取可用模型列表"""
        try:
            response = self.deepseek.models()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"获取模型列表失败: {str(e)}")

    def get_usage(self) -> Dict[str, Any]:
        """获取API使用情况"""
        try:
            response = self.deepseek.usage()
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"获取使用情况失败: {str(e)}")


# 自定义异常
class RateLimitError(Exception):
    """API速率限制异常"""
    pass